<!-- components/LocationPicker.vue -->
<template>
  <div class="map-container">
    <div id="map" style="height: 250px"></div>
    <div class="controls">
      <div v-if="loading" class="loading">定位中...</div>
    </div>
    <div class="tip">
      <div v-if="currentAccuracy" class="accuracy">精度范围：{{ currentAccuracy }}米</div>
    </div>
  </div>
  <el-form-item label="签到范围" prop="range" style="margin-top: 20px;">
    <el-select 
        style="width:180px; margin-left: 20px" 
        v-model="data.radius" 
        @change="fetchData" 
        placeholder="签到范围"
      >
        <el-option label="50米" value="50" />
        <el-option label="100米" value="100" />
        <el-option label="200米" value="200" />
        <el-option label="500米" value="500" />
      </el-select>
  </el-form-item>
</template>

<script setup>
/* eslint-disable no-undef */
import { reactive, defineExpose } from 'vue';
import { onMounted, onUnmounted, ref } from 'vue'
import axios from 'axios';
const emit = defineEmits(['update:modelValue'])
const mapInstance = ref(null)
const marker = ref(null)
const circle = ref(null)
const geolocation = ref(null)
const loading = ref(false)
const currentAccuracy = ref(null)
const eventListeners = ref([]) // 存储事件监听器
const API_BASE = 'http://localhost:8080/session'
const api = {
  create: `${API_BASE}/addMap`,
}
const data = reactive({
  sessionType: '位置',
  latitude: null,
  longitude: null,
  radius: null
})

// 组件卸载时清理
onUnmounted(() => {
  destroyMap()
})

// 安全初始化地图
const initMap = () => {
  try {
    if (typeof AMap === 'undefined') {
      loadAMapAPI()
    } else {
      initializeAMap()
      loadGeolocationPlugin(true)
    }
  } catch (error) {
    console.error('地图初始化异常:', error)
    alert('地图加载失败，请刷新页面重试')
  }
}

// 加载高德地图API
const loadAMapAPI = () => {
  const script = document.createElement('script')
  script.src = `https://webapi.amap.com/maps?v=1.4.15&key=f258cbb4425c5fcef681b6a3ff368e3d`
  script.onload = () => {
    initializeAMap()
    loadGeolocationPlugin(true)
  }
  script.onerror = () => {
    console.error('地图API加载失败')
    alert('地图服务加载失败，请检查网络连接')
  }
  document.body.appendChild(script)
}

// 初始化地图实例
const initializeAMap = () => {
  try {
    mapInstance.value = new AMap.Map('map', {
      zoom: 17,
      center: [116.397428, 39.90923],
      doubleClickZoom: false
    })

    // 添加防抖的移动结束监听
    const moveEndHandler = debounce(() => {
      console.log('地图移动结束')
    }, 300)

    // 保存事件监听器以便销毁
    const clickListener = mapInstance.value.on('click', handleMapClick)
    const moveEndListener = mapInstance.value.on('moveend', moveEndHandler)
    
    eventListeners.value.push(clickListener, moveEndListener)
  } catch (error) {
    console.error('地图创建失败:', error)
    alert('地图初始化失败')
  }
}

// 处理地图点击事件
const handleMapClick = (e) => {
  if (!mapInstance.value) return
  
  try {
    // 创建新的坐标对象
    const newPos = new AMap.LngLat(
      e.lnglat.getLng() + 0.0052,
      e.lnglat.getLat() - 0.0015
    )
    setMarker(newPos)
    currentAccuracy.value = null
    emitPosition(newPos)
  } catch (error) {
    console.error('地图点击处理失败:', error)
  }
}

// 加载定位插件
const loadGeolocationPlugin = (autoLocate = false) => {
  try {
    AMap.plugin('AMap.Geolocation', () => {
      geolocation.value = new AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 10000,
        showButton: false,
        extensions: 'all'
      })
      if (autoLocate) locate()
    })
  } catch (error) {
    console.error('定位插件加载失败:', error)
  }
}

// 定位逻辑
const locate = () => {
  if (!geolocation.value) return
  
  loading.value = true
  geolocation.value.getCurrentPosition((status, result) => {
    loading.value = false
    status === 'complete' 
      ? handleLocateSuccess(result.position, result.accuracy)
      : handleLocateError(result)
  })
}

// 处理定位成功
const handleLocateSuccess = (position, accuracy) => {
  try {
    // 创建新坐标对象
    const adjustedPos = new AMap.LngLat(
      position.getLng() + 0.0052,
      position.getLat() - 0.0015
    )
    
    setMarker(adjustedPos)
    updateAccuracyCircle(adjustedPos, accuracy)
    
    if (mapInstance.value) {
      mapInstance.value.setCenter(adjustedPos)
      mapInstance.value.setZoom(17)
    }
    
    currentAccuracy.value = Math.round(accuracy)
    emitPosition(adjustedPos, accuracy)
  } catch (error) {
    console.error('定位处理失败:', error)
    loading.value = false
  }
}

// 更新精度范围
const updateAccuracyCircle = (center, radius) => {
  try {
    if (circle.value) circle.value.setMap(null)
    
    circle.value = new AMap.Circle({
      center: center,
      radius: radius,
      strokeColor: "#409eff",
      strokeOpacity: 0.5,
      strokeWeight: 2,
      fillColor: "#409eff",
      fillOpacity: 0.1,
      map: mapInstance.value
    })
  } catch (error) {
    console.error('精度圈更新失败:', error)
  }
}

// 设置标记
const setMarker = (lnglat) => {
  try {
    if (marker.value) marker.value.setMap(null)
    
    marker.value = new AMap.Marker({
      position: lnglat,
      map: mapInstance.value
    })
  } catch (error) {
    console.error('标记设置失败:', error)
  }
}

const emitPosition = (lnglat, accuracy) => {
  try {
    // 更新 data 中的经纬度
    data.latitude = lnglat.getLat();
    data.longitude = lnglat.getLng();
    
    // 原有 emit 逻辑保持不变
    emit('update:modelValue', {
      lng: lnglat.getLng(),
      lat: lnglat.getLat(),
      accuracy: accuracy ? Math.round(accuracy) : null
    });
  } catch (error) {
    console.error('位置传递失败:', error);
  }
};


// 销毁地图资源
const destroyMap = () => {
  try {
    // 移除所有事件监听
    eventListeners.value.forEach(listener => {
      mapInstance.value?.off(listener)
    })
    
    if (mapInstance.value) {
      mapInstance.value.destroy()
      mapInstance.value = null
    }
  } catch (error) {
    console.error('地图销毁失败:', error)
  }
}

// 防抖函数
const debounce = (fn, delay) => {
  let timer
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}
const handleCreate = async () => {
  try {
    // 数据校验
    if (!data.latitude || !data.longitude) {
      throw new Error('请先选择位置');
    }
    if (!data.radius) {
      throw new Error('请设置签到范围');
    }

    // 构造请求数据
    const payload = {
      sessionType: data.sessionType,
      latitude: Number(data.latitude), // 转换为数字
      longitude: Number(data.longitude),
      radius: Number(data.radius)
    };
    console.log(payload)
    // 发送请求
    const response = await axios.post(api.create, payload);
    return response.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || error.message);
  }
};
defineExpose({
  handleCreate,
  data
})
onMounted(initMap)
</script>

<style>
#map {
  min-height: 250px;
  max-height: 70vh;
  width: 100%;
  background: #f0f2f5;
  transition: opacity 0.3s;
}

/* 加载时的渐变效果 */
#map[data-loading="true"] {
  opacity: 0.5;
  pointer-events: none;
}

/* 错误状态提示 */
.map-error {
  border: 2px solid #ff4d4f;
  animation: pulseAlert 1.5s infinite;
}

@keyframes pulseAlert {
  0% { border-color: #ff4d4f; }
  50% { border-color: #ff7875; }
  100% { border-color: #ff4d4f; }
}
.map-container {
  width: 100%;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 10px;
  position: relative;
}

.controls {
  margin: 10px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.locate-btn {
  background: #409eff;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
}

.locate-btn:hover {
  background: #66b1ff;
}

.tip {
  color: #666;
  font-size: 12px;
  margin-top: 8px;
}

.accuracy {
  color: #409eff;
  font-weight: bold;
  margin-top: 4px;
}

.loading {
  color: #666;
  font-size: 12px;
}
</style>